<template>
  <d2-container class="page">
    <div class="page-form">
      <el-form :inline="true" :model="queryForm">
        <!-- <el-form-item label="开始年龄">
          <el-input-number v-model="queryForm.startAge" :min="0" :max="100"></el-input-number>
        </el-form-item> -->
        <!-- <el-form-item label="结束年龄">
          <el-input-number v-model="queryForm.endAge" :min="1" :max="100"></el-input-number>
        </el-form-item> -->
        <el-form-item label="分组" prop="groups" label-width="50px">
          <el-cascader
            style="width: 330px"
            :options="parentData"
            :props="cascaderProps"
            v-model="queryForm.groups"
            clearable
            collapse-tags
          ></el-cascader>
        </el-form-item>
        <!-- <el-form-item label="标签">
          <el-select v-model="queryForm.labels" multiple collapse-tags style="width: 100%;" clearable>
            <el-option v-for="(item, index) in labelData"
                       :key="'label' + index"
                       :label="item.value"
                       :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="性别">
          <el-select v-model="queryForm.sex" style="width: 100%;" clearable>
            <el-option v-for="(item, index) in sexArr"
                       :key="'sex' + index"
                       :label="item.value"
                       :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- <br> -->
        <!-- <el-form-item label="VIP等级">
          <el-select v-model="queryForm.vipGrade" style="width: 100%;" clearable>
            <el-option v-for="(item, index) in vipData"
                       :key="'vip' + index"
                       :label="item.value"
                       :value="item.code"
            ></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="审核状态">
          <el-select v-model="queryForm.status" style="width: 100%;" clearable>
            <el-option label="待审核" value="0"></el-option>
            <el-option label="审核通过" value="1"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="用户名">
          <el-input v-model="queryForm.wxName" placeholder="请输入" clearable></el-input>
        </el-form-item> -->
        <el-form-item label="手机号">
          <el-input v-model="queryForm.wxPhone" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item label="微信昵称">
          <el-input v-model="queryForm.wxNickname" placeholder="请输入" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="page-table person-table">
      <el-button type="primary" @click="onMessage('all')">群发消息</el-button>

      <el-table
        :data="tableData"
        :loading="loading"
        style="width: 100%"
        row-key="id"
        ref="table"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="wxHeadimgurl" label="头像">
          <template slot-scope="scope">
            <el-avatar size="medium" shape="square" :src="scope.row.wxHeadimgurl"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="wxNickname" label="微信昵称"></el-table-column>
        <!-- <el-table-column prop="wxName" label="用户名"></el-table-column> -->
        <el-table-column prop="wxPhone" label="手机号"></el-table-column>
        <el-table-column prop="wxSex" label="性别"></el-table-column>
        <!-- <el-table-column prop="age" label="年龄"></el-table-column> -->
        <!-- <el-table-column prop="completeOrderCnt" label="已完成派单"></el-table-column> -->
        <!-- <el-table-column prop="labels" label="标签">
          <template slot-scope="scope">
            <el-tag size="mini"
                    v-for="(item, index) in scope.row.labels"
                    :key="'slable' + index">{{labelObj[item]}}</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="groups" label="分组">
          <template slot-scope="scope">
            <el-tag size="mini"
                    type="danger"
                    v-for="(item, index) in scope.row.groups"
                    :key="'sgroup' + index">{{groupObj[item]}}</el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="integral" label="积分"></el-table-column> -->
        <!-- <el-table-column prop="vipGrade" label="vip等级"></el-table-column> -->
        <!-- <el-table-column prop="status" label="审核状态">
          <template slot-scope="scope">
            <el-tag size="mini" v-if="scope.row.status === 0">待审核</el-tag>
            <el-tag size="mini" v-else-if="scope.row.status === 1" type="success">审核通过</el-tag>
          </template>
        </el-table-column> -->
        <el-table-column prop="introduce" label="备注"></el-table-column>
        <el-table-column label="操作" width="300">
          <template slot-scope="scope">
            <!-- <p> -->
              <el-button type="primary" size="small"
                         @click="onInfo({index: scope.$index, row: scope.row})"
              >详情</el-button>
              <el-button type="primary" size="small"
                         @click="onIntro({index: scope.$index, row: scope.row})"
              >备注</el-button>
            <!-- </p> -->
            <!-- <p> -->
              <el-button type="success" size="small"
                         @click="onGroup({index: scope.$index, row: scope.row})"
              >绑定分组</el-button>
            <!-- </p> -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        layout="prev, pager, next, jumper, total, sizes"
        :page-sizes="[5, 20, 50, 100, 200, 500, 1000]"
        :page-size="queryForm.limit"
        :current-page="queryForm.page"
        :total="pagination.total"
        @current-change="pageChange"
        @size-change="sizeChange">
      </el-pagination>
    </div>

    <!--  详情  -->
    <person-info
      v-if="visibleInfo"
      :visible="visibleInfo"
      :info="currRow"
      @close="closeInfo"
      @examine="examine"/>
    <!--  绑定分组  -->
    <person-group
      v-if="visibleGroup"
      :visible="visibleGroup"
      :info="currRow"
      @cancel="cancelGroup"
      @submit="submitGroup"
    />
    <!--调整积分-->
    <el-dialog
      title="修改积分"
      width="1000px"
      v-if="visibleScore"
      :visible.sync="visibleScore"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false">
      <div class="score-content">
        <el-table :data="creditData" :loading="loadingScore" height="500px" style="width: 100%">
          <el-table-column prop="createTime" label="调整时间"></el-table-column>
          <el-table-column prop="creditVal" label="分值"></el-table-column>
          <el-table-column prop="creditDesc" label="调整依据"></el-table-column>
        </el-table>

        <el-form :model="scoreForm" :rules="scoreRules" ref="scoreForm">
          <el-form-item label="当前分值" label-width="100px">
            {{currScore}}
          </el-form-item>
          <el-form-item label="调整分值" prop="creditVal" label-width="100px">
            <el-input type="age" v-model.number="scoreForm.creditVal" autocomplete="off" clearable></el-input>
          </el-form-item>
          <el-form-item label="调整依据" prop="creditDesc" label-width="100px">
            <el-input type="textarea" v-model="scoreForm.creditDesc" autocomplete="off" clearable></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelScore">取 消</el-button>
        <el-button type="primary" @click="submitScore">确 定</el-button>
      </span>
    </el-dialog>
    <!--群发消息-->
    <send-msg
      v-if="visibleGroupMsg"
      :visible="visibleGroupMsg"
      :openType="openType"
      @cancel="cancelGroupMsg"
      @submit="submitGroupMsg"
    />
    <!--消息列表-->
    <message-list
      v-if="visibleMsgList"
      :visible="visibleMsgList"
      :info="currRow"
      @submit="submitMsgList"
    />
  </d2-container>
</template>

<script>
import { mapActions } from 'vuex'
import util from '@/libs/util.js'
import PersonInfo from './person-info'
import PersonGroup from './person-group'
import SendMsg from './send-msg'
import MessageList from './message-list'

export default {
  name: 'person',
  data () {
    return {
      loading: false,
      groupData: null,
      labelData: null,
      labelObj: {},
      groupObj: {},
      sexData: {},
      sexArr: [],
      visibleInfo: false,
      visibleGroup: false,
      visibleScore: false,
      visibleGroupMsg: false,
      visibleMsgList: false,
      currRow: null,
      queryForm: {
        page: 1,
        limit: 5,
        sex: '',
        startAge: 0,
        endAge: 100,
        labels: [],
        groups: [],
        status: '',
        wxName: '',
        wxPhone: '',
        wxNickname: '',
        vipGrade: ''
      },
      pagination: {
        total: 0
      },
      tableData: [],
      creditData: [],
      vipData: [],
      loadingScore: false,
      scoreForm: {
        userId: '',
        creditVal: '',
        creditDesc: ''
      },
      scoreRules: {
        creditVal: [
          { required: true, message: '请调整分值', trigger: 'blur' },
          { type: 'number', message: '只能输入数字', trigger: 'blur' }
        ],
        creditDesc: [
          { required: true, message: '请输入调整依据', trigger: 'blur' }
        ]
      },
      currScore: '',
      parentData: [],
      cascaderProps: {
        checkStrictly: false,
        value: 'id',
        label: 'name',
        children: 'list',
        multiple: true
      },
      selData: [],
      singleData: [],
      sendType: '',
      openType: '0',
      msgForm: {
        title: '',
        content: '',
        type: '',
        receiveUserIds: []
      }
    }
  },
  components: {
    PersonInfo,
    PersonGroup,
    SendMsg,
    MessageList
  },
  created () {
    this.getDictionary('')
    // const dict = util.cookies.get('dictionary')
    // console.log('dict000', dict)
    // if (dict) {
    //   this.labelData = JSON.parse(dict).label
    //   this.labelData.forEach(item => {
    //     this.labelObj[item.code] = item.value
    //   })
    //   const sexs = JSON.parse(dict).sex
    //   this.sexArr = sexs
    //   sexs.forEach(item => {
    //     this.sexData[item.code] = item.value
    //   })

    //   this.vipData = JSON.parse(dict).vip
    // }

    this.queryGroupList()
    this.getGroupTree()
  },
  mounted () {
    this.queryList()
  },
  methods: {
    ...mapActions('d2admin/sys.person', [
      'personList',
      'personScore',
      'personRemark',
      'creditList',
      'sendMessage',
      'test'
    ]),
    ...mapActions('d2admin/pm.group', [
      'groupList',
      'groupTree'
    ]),
    ...mapActions('d2admin/pm.dictionary', [
      'dictLoad'
    ]),
    // 获取字典
    getDictionary (type) {
      this.dictLoad({ type }).then(res => {
        console.log('pm', res)
        const dict = res
        this.labelData = dict.label
        this.labelData.forEach(item => {
          this.labelObj[item.code] = item.value
        })
        const sexs = dict.sex
        this.sexArr = sexs
        sexs.forEach(item => {
          this.sexData[item.code] = item.value
        })

        // if (type === 'country') {
        //   this.locationOptions = res.country
        // }
      })
    },
    test () {
      console.log('test0')
      this.test().then(res => {
        console.log(res, 'test')
      })
    },
    // 查询列表
    queryList () {
      this.loading = true
      const form = JSON.parse(JSON.stringify(this.queryForm))
      if (this.queryForm.groups.length > 0) {
        form.groups = this.queryForm.groups.reduce((a, b) => {
          return a.concat(b)
        })
      }
      this.personList(form).then(
        res => {
          this.loading = false
          res.list.forEach(item => {
            if (item.wxSex) {
              item.wxSex = this.sexData[item.wxSex]
              item.introduce = item.introduce || '无'
            }
          })

          this.tableData = res.list
          this.pagination.total = res.totalCount
        }
      ).catch(err => {
        this.loading = false
      })
    },
    // 其他用途调用
    queryHandle (page) {
      this.queryForm.page = page
      this.queryList()
    },
    // 切换分页
    pageChange (curr) {
      this.queryHandle(curr)

      // 遍历勾选数据，设置回显
      // this.$nextTick(() => {
      //   this.allData.forEach(item => {
      //     console.log(item)
      //     this.$refs.table.toggleRowSelection(item, true)
      //   })
      // })
    },
    // 切换每页显示条数
    sizeChange (val) {
      this.queryForm.page = 1
      this.queryForm.limit = val
      this.queryList()
    },
    // 点击查询按钮
    onSubmit () {
      this.queryHandle(1)
    },
    // 查询分组列表
    queryGroupList () {
      this.groupList({}).then(res => {
        this.groupData = res
        this.groupData.forEach(item => {
          this.groupObj[item.id] = item.name
        })
      })
    },
    // 查询分组树
    getGroupTree () {
      this.groupTree().then(
        res => {
          this.parentData = res
        }
      )
    },
    // 打开详情列表
    onInfo ({ index, row }) {
      this.currRow = row
      this.visibleInfo = true
    },
    // 关闭详情
    closeInfo (visible) {
      this.visibleInfo = visible
    },
    // 绑定分组
    onGroup ({ index, row }) {
      this.currRow = row
      this.visibleGroup = true
    },
    // 取消绑定分组
    cancelGroup (visible) {
      this.visibleGroup = visible
    },
    // 提交绑定分组
    submitGroup (visible) {
      this.visibleGroup = visible
      this.queryList()
    },
    // 查询积分明细
    getCreditList (id) {
      this.loadingScore = true
      this.creditList({
        userId: id
      }).then(res => {
        this.creditData = res
        this.loadingScore = false
      })
    },
    // 手动调整积分
    onScore ({ index, row }) {
      this.scoreForm.userId = row.userId
      this.scoreForm.creditVal = ''
      this.currScore = Number(row.integral)
      this.visibleScore = true
      this.$nextTick(() => {
        this.getCreditList(row.userId)
      })
    },
    // 取消修改积分
    cancelScore () {
      this.scoreForm.userId = null
      this.scoreForm.creditVal = null
      this.visibleScore = false
    },
    // 提交修改积分
    submitScore () {
      this.$refs.scoreForm.validate(valid => {
        if (valid) {
          this.personScore(this.scoreForm).then(
            res => {
              this.queryList()
              this.visibleScore = false
            }
          )
        }
      })
    },
    // 审核
    examine (visible) {
      this.visibleInfo = visible
      this.queryList()
    },
    // 备注信息
    onIntro ({ index, row }) {
      this.$prompt('请输入备注信息', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '请输入备注信息'
      }).then(({ value }) => {
        this.personRemark({
          userId: row.userId,
          introduce: value
        }).then(
          res => {
            this.queryList()
          }
        )
      }).catch((err) => {
        console.log(err)
      })
    },
    // 勾选人员
    handleSelectionChange (val) {
      val.forEach(row => {
        this.selData.push(row)
      })
    },
    // 打开发送消息
    onMessage (type, row) {
      this.visibleGroupMsg = true
      this.sendType = type
      if (this.sendType === 'single') {
        this.openType = '0'
        this.singleData = []
        this.singleData.push(row)
      } else if (this.sendType === 'all') {
        this.openType = '1'
      }
    },
    // 关闭群发消息
    cancelGroupMsg (visible) {
      this.visibleGroupMsg = visible
    },
    // 确定群发消息
    submitGroupMsg (visible, data) {
      this.msgForm = data
      this.msgForm.receiveUserIds = []
      const users = []
      let selectedData = null
      if (this.sendType === 'single') {
        selectedData = this.singleData
      } else if (this.sendType === 'all') {
        selectedData = this.selData
      }
      if (selectedData.length === 0) {
        this.$message.error('请勾选人员')
        return false
      }
      new Promise((resolve, reject) => {
        selectedData.forEach(item => {
          users.push(item.userId)
        })
        resolve(users)
      }).then(response => {
        this.msgForm.receiveUserIds = response

        this.sendMessage(this.msgForm).then(
          res => {
            this.visibleGroupMsg = visible
          }
        )
      })
    },
    // 打开消息列表
    onMessageList ({ index, row }) {
      this.visibleMsgList = true
      this.currRow = row
    },
    // 关闭消息列表
    submitMsgList (visible) {
      this.visibleMsgList = visible
    }
  }
}
</script>

<style lang="scss">
  .page {
    .page-form {
      border: 1px solid #eee;
      padding: 20px 20px 0;
    }
    .page-table {
      border: 1px solid #eee;
      padding: 20px;
      margin-top: 20px;
      &.person-table {
        .el-tag {
          margin: 2px;
        }
      }
    }
    .el-pagination {
      padding: 30px 0 15px;
      .el-pagination__total {
        float: right;
      }
    }
  }

  .score-content {
    display: flex;
    .el-table {
      flex: 1;
    }
    .el-form {
      width: 300px;
    }
  }
</style>
